import ConfigReader from '../utils/configReader';
import { info, error } from '../utils/logger';
import { randomCode, ASCIISortToString, urlEncode, getClientIP } from '../utils';
import jsonxml from 'jsontoxml'
import { to_json } from 'xmljson'
const express = require('express'), app = express();
const request = require("request");
const { key, notifyUrl, payNotifyRoute, mchid, appid, subMch, subAppid } = new ConfigReader("./server/config/pay.json").get("wechat");
var md5 = require("md5")
const fs = require("fs");
app.use('/pay', async (req, res, next) => {
    const { price, openid } = req.body;
    const ip = await getClientIP();
    let payBody = {
        body: "支付订单",
        nonce_str: randomCode(30),
        out_trade_no: randomCode(30),
        total_fee: 100,//单位:分
        spbill_create_ip: ip,
        notify_url: notifyUrl + payNotifyRoute,
        trade_type: "JSAPI",
        mch_id: mchid,
        appid: appid,
        sub_mch_id: subMch,
        sub_appid: subAppid,
        sub_openid: "odr4W0ca2SKyWjDWk7QBtOReSho8",
        // attach不能为空字符串 签名会报错 urlEncode方法不完善
        attach: "支付测试",
    };
    // 按ASCII排序上面的键值对
    payBody = ASCIISortToString(payBody);
    // 必在encode后的字符串后面加上key参数
    const encodeBody = urlEncode(payBody, true, true) + `&key=${key}`;
    payBody.sign = md5(encodeBody).toUpperCase();
    // 转换成xml格式发送请求
    const xmlData = jsonxml({ xml: payBody });
    request({
        url: "https://api.mch.weixin.qq.com/pay/unifiedorder",
        method: 'POST',
        body: xmlData
    }, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            to_json(body, (err, { xml: data }) => {
                if (!err) {
                    const timeStamp = Date.now() + "";
                    const packageStr = `prepay_id=${data['prepay_id']}`;
                    //签名
                    const signParams = ASCIISortToString({ appId: "wxf45dce483764af11", package: packageStr, nonceStr: data["nonce_str"], signType: "MD5", timeStamp });
                    const encodeBody = urlEncode(signParams, true, true) + `&key=${key}`;
                    info(encodeBody);
                    const paySign = md5(encodeBody).toUpperCase();
                    // 返回签名处理后的值
                    res.json({ ...data, timeStamp, prepay_id: packageStr, sign: paySign });
                } else {
                    res.status(500).json(err);
                }
            });
        } else {
            error(err);
            res.status(500).json(err);
        }
    });
});
// https://ec06e790.ngrok.io
app.use('/payToPersonal', async (req, res, next) => {
    const { price, openid } = req.body;
    const ip = await getClientIP();
    // let payBody = {
    //     mch_appid:appid,
    //     mchid:mchid,
    //     nonce_str:randomCode(32),
    //     partner_trade_no:randomCode(32),
    //     openid:"oSpOwxDTBDmo8-WztTCewO-vbQb4",
    //     // openid:"o7fRY5IwSKT2ZolWS0LX1B7vqABY",
    //     check_name:"FORCE_CHECK",
    //     re_user_name:"王杰",
    //     amount:100,
    //     desc:"测试",
    //     spbill_create_ip:ip,
    // };
    let payBody = {
        mch_appid:"wxf45dce483764af11",
        mchid:"1504806891",
        nonce_str:randomCode(32),
        partner_trade_no:randomCode(32),
        // openid:"oSpOwxDTBDmo8-WztTCewO-vbQb4",
        openid:"o7fRY5IwSKT2ZolWS0LX1B7vqABY",
        check_name:"FORCE_CHECK",
        re_user_name:"王杰",
        amount:100,
        desc:"测试",
        spbill_create_ip:ip,
    };
    // 按ASCII排序上面的键值对
    payBody = ASCIISortToString(payBody);
    // 必在encode后的字符串后面加上key参数
    const encodeBody = urlEncode(payBody, true, true) + `&key=${key}`;
    payBody.sign = md5(encodeBody).toUpperCase();
    // 转换成xml格式发送请求
    const xmlData = jsonxml({ xml: payBody });
    info(xmlData);
    request({
        url: "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers",
        method: 'POST',
        agentOptions: {
            pfx: fs.readFileSync('./cert/apiclient_cert.p12'), //微信商户平台证书,
            passphrase: "1504806891" // 商家id
        },
        body: xmlData
    }, function (err, response, body) {
        if (!err && response.statusCode == 200) {
            to_json(body, (err, { xml }) => {
                if (!err) {
                    res.json(xml);
                } else {
                    res.status(500).json(err);
                }
            });
        } else {
            error(err);
            res.status(500).json(err);
        }
    });
});

app.get("/authed",async (req,res)=>{
    res.sendfile("E:\\nodejs\\a.html");
})
export default app;
